package com.amphiprion.prototype.component;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;

import com.amphiprion.prototype.ScreenProperty;
import com.amphiprion.prototype.control.ControlerState;
import com.amphiprion.prototype.control.ControlerState.ClickMode;

public class AreaComponent extends GameComponent {
	private IActionListener listener;
	private Paint paint;
	protected float width;
	protected float height;

	public AreaComponent(int color, float x, float y, float width, float height, int alpha) {
		super();
		this.width = width;
		this.height = height;
		this.x = x;
		this.y = y;
		this.alpha = alpha;
		paint = new Paint();
		paint.setColor(color);
		paint.setStyle(Style.FILL);
	}

	@Override
	public void onInput(ControlerState state, long elapsed) {
		super.onInput(state, elapsed);
		if (listener != null) {
			if (state.click == ClickMode.DOWN) {
				if (isInside(state.position.x, state.position.y)) {
					listener.actionPerformed(this);
				}
			}
		}
	}

	public boolean isInside(float px, float py) {
		if (px >= x - width * scale / 2 && px <= x + width * scale / 2) {
			if (py >= y - height * scale / 2 && py <= y + height * scale / 2) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onDraw(Canvas canvas, ScreenProperty screenProperty) {
		if (alpha == 0) {
			return;
		}
		paint.setAlpha(alpha);
		drawFillRect(canvas, x - width * scale / 2, y - height * scale / 2, x + width * scale / 2, y + height * scale / 2, screenProperty);
	}

	protected void drawFillRect(Canvas canvas, float left, float top, float right, float bottom, ScreenProperty screenProperty) {

		Matrix m = new Matrix();
		// m.postTranslate(-canvas.getWidth() / 2, -canvas.getHeight() / 2);
		m.postRotate(screenProperty.screenRotation);
		if (screenProperty.screenRotation == 0) {
			// m.postTranslate(canvas.getWidth() / 2, canvas.getHeight() / 2);
		} else {
			m.postTranslate(canvas.getWidth(), 0);
			// m.postTranslate(canvas.getHeight() / 2, canvas.getWidth() / 2);
		}
		canvas.save();
		canvas.setMatrix(m);
		canvas.rotate(rotation, x * screenProperty.screenScale, y * screenProperty.screenScale);
		canvas.drawRect(left * screenProperty.screenScale, top * screenProperty.screenScale, right * screenProperty.screenScale, bottom * screenProperty.screenScale, paint);
		canvas.restore();

	}

	public void setActionListener(IActionListener listener) {
		this.listener = listener;
	}

	@Override
	public void activate() {
		// Nothing to do
	}

	@Override
	public void desactivate() {
		// Nothing to do
	}

	public float getWidth() {
		return width;
	}

	public float getHeight() {
		return height;
	}

	public void setColor(int color) {
		paint.setColor(color);
	}
}
